// pages/login/index.js
const {
  scanAuth,
  scanAuthReview,
  scanPlannerLogin
} = require('../../api/planner')
const config = require("../../config/config");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAgree: true,
    type: 'login'
  },

  changeStatus(e) {
    this.setData({
      isAgree: !this.data.isAgree
    })
  },
  checkIsAgree() {
    const {
      isAgree
    } = this.data
    if (!isAgree) {
      wx.showToast({
        title: '请先同意用户服务协议及隐私政策',
        icon: 'none'
      })
      return
    }
  },
  async auth() {
    const {
      type
    } = this.data
    if(type=='planner'){
      const params = {
        scene: this.data.scene
      }
      const {
        result
      } = await scanPlannerLogin(params)
      wx.navigateBack()
    }else if (type == 'login') {
      const params = {
        scene: this.data.scene
      }
      const {
        result
      } = await scanAuth(params)
      wx.navigateBack()
    } else {
      const {
        studentId
      } = this.data
      const {
        result
      } = await scanAuthReview(studentId)
      wx.navigateBack()
    }

  },
  async getPhoneNumber(e) {
    var that = this
    if (!e.detail.iv) return
    wx.showLoading({
      title: '授权中',
    })
    const {
      encryptedData,
      iv
    } = e.detail
    var {
      code
    } = this.data
    const param = {
      code,
      encryptedData,
      iv,
      promoteUser: wx.getStorageSync('promoteUser'),
      spreadUserId: wx.getStorageSync('spreadUserId')
    }
    console.log(param)
    const data = await wxMobileLogin(param)
    wx.hideLoading()
    if (data.success) {
      const {
        userInfo,
        token
      } = data.result
      let newTime = Math.round(new Date())
      wx.setStorageSync(config.storageKey.loginTime, newTime);
      wx.setStorageSync(config.storageKey.token, token)
      that.fetchUserInfo()
      wx.hideLoading()
      if (!userInfo.mobile == '') {
        wx.setStorageSync(config.storageKey.mobile, userInfo.mobile)
      }
    }
  },
  goto(e) {
    const {
      url
    } = e.currentTarget.dataset
    wx.navigateTo({
      url,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.scene) {
      this.setData({
        scene: options.scene
      })
    }
    if (options.studentId) {
      this.setData({
        studentId: options.studentId
      })
    }
    if (options.type) {
      this.setData({
        type: options.type
      })
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})